<template>
  <TrLayout
    v-model="checkPopup"
    :title="title"
    :width="width"
    :zIndex="zIndex"
    @close="closeHandle"
    @confrim="confrimHandle"
  >
    <div class="power-content-wrap bd-rd-4 fx of-hd bd-dc-1">
      <div class="power-left bd-e7-rt fx fx-cl fx-sk">
        <div class="ft-14 ht-48 cr-bk-9 lh-48 pd-lf-16 bg-f8 fx-sk">
          {{ leftTitle }}
        </div>
        <div class="mg-16 fx-sk">
          <el-input
            v-model="searchLeftKey"
            :placeholder="leftPlaceholder"
            type="text"
            clearable
            @keydown.native.enter="searchLeftHandle"
            @clear="searchLeftHandle"
          >
            <i
              slot="prefix"
              class="el-input__icon el-icon-search"
              @click="searchLeftHandle"
            ></i>
          </el-input>
        </div>
        <div
          class="scroll-wrap fx-full of-y-sr mg-bt-16 mg-lt-16 mg-rt-8"
          v-infinite-scroll="requestHandle"
          infinite-scroll-disabled="false"
          infinite-scroll-immediate="true"
          infinite-scroll-distance="1"
        >
          <div
            class="t-item ft-14 ht-28 mg-bt-8 mg-rt-8 pd-lf-8 pd-rt-8 fx-ag-ct bd-rd-3 ts-al cs-pt"
            :class="{ checked: ids.includes(item.rlValue) }"
            v-for="(item, index) in dataList"
            :key="index"
            @click="chooseHandle(item)"
          >
            <div
              v-if="selectModel == 'single'"
              class="radio-icon ht-16 wd-16 bd-rd-50 bd-dc-1 mg-rt-8"
            ></div>
            <div
              v-else
              class="check-icon ht-16 wd-16 bd-rd-3 bd-dc-1 mg-rt-8"
            ></div>
            {{ item.rlLabel }}
          </div>
          <div class="load-tips ht-28 lh-28 ft-14">
            {{ isLoadAll ? "到底了~" : "加载中..." }}
          </div>
        </div>
      </div>
      <div class="power-right">
        <div class="ht-48 pd-16 fx-bt-ct bg-f8">
          <div class="ft-14 cr-bk-9">{{ rightTitle }}</div>
          <el-input
            v-model="searchRightKey"
            class="wd-240"
            type="text"
            clearable
            :placeholder="rightPlaceholder"
            @keydown.native.enter="searchRightHandle"
            @clear="searchRightHandle"
          >
            <i
              slot="prefix"
              class="el-input__icon el-icon-search"
              @click="searchRightHandle"
            ></i>
          </el-input>
        </div>
        <div class="right-content-wrap">
          <TrTable
            ref="trTable"
            isPopup
            :isNeedSelection="rightRequstObj && rightRequstObj.isNeedSelection"
            :tableColumn="tableColumn"
            :tableData="tableData"
            :checkedList.sync="checkedListSync"
            :isNeedPagination="false"
          />
          <TrFooter
            ref="trFooter"
            v-model="rightParams"
            :total="totalNum"
            isDeepSearch
            layout="sizes, prev, pager, next"
            requestName="getTableList"
            :rowKeyStr="rightRequstObj && rightRequstObj.rowKeyStr"
            :pageCount="5"
            @footer-search="footerSearch"
          />
        </div>
      </div>
    </div>
  </TrLayout>
</template>

<script>
import TrFooter from "@/components/Tr-footer/Tr-footer.vue";
import TrLayout from "../Tr-layout/Tr-layout.vue";
import TrTable from "../Tr-table/Tr-table.vue";
import { getDataList } from "@/api/base/base";
export default {
  name: "TrPowerBox",
  components: {
    TrLayout,
    TrTable,
    TrFooter,
  },
  props: {
    leftEmptyTip: {
      type: String,
      default: "请选择人员",
    },
    leftPlaceholder: {
      type: String,
      default: "请输入姓名",
    },
    rightEmptyTip: {
      type: String,
      default: "请选择工站",
    },
    rightPlaceholder: {
      type: String,
      default: "请输入工站名称",
    },
    selectModel: {
      type: String,
      default: "single",
    },
    zIndex: {
      type: Number,
      default: 1001,
    },
    title: {
      type: String,
      default: "权限分配",
    },
    value: {
      type: Boolean,
      default: false,
    },
    width: {
      type: Number,
      default: 1227,
    },
    leftTitle: {
      type: String,
      default: "用户列表",
    },
    rightTitle: {
      type: String,
      default: "工站列表",
    },
    leftRequstObj: {
      type: Object,
      default: () => {},
    },
    leftDefaultParams: {
      type: Object,
      default: () => {},
    },
    rightRequstObj: {
      type: Object,
      default: () => {},
    },
    rightDefaultParams: {
      type: Object,
      default: () => {},
    },
    tableColumn: {
      type: Array,
      default: () => [],
    },
    checkedList: {
      type: Array,
      default: () => [],
    },
  },
  data: () => ({
    selectValue: {},
    searchLeftKey: "",
    searchRightKey: "",
    isRequestFlag: false,
    isLoadAll: false,
    dataList: [],
    leftParams: {
      current: 1,
      size: 30,
    },
    rightParams: {
      current: 1,
      size: 10,
    },
    tableData: [],
    totalNum: 0,
  }),
  watch: {
    value(newVal) {
      if (!newVal) {
        this.resetParamsHandle();
        return;
      }
      this.initValue();
      this.getDataList();
      this.getTableList();
    },
  },
  computed: {
    checkedListSync: {
      get() {
        return this.checkedList;
      },
      set(val) {
        this.$emit("update:checkedList", val);
      },
    },
    checkPopup() {
      return this.value;
    },
    ids() {
      if (this.selectModel == "single") return [this.selectValue.rlValue];
      return (
        (Array.isArray(this.selectValue) &&
          this.selectValue.map((item) => item.rlValue)) ||
        []
      );
    },
  },
  methods: {
    footerSearch(obj) {
      const { currentPage, pageSize } = obj;
      this.rightParams.current = currentPage;
      this.rightParams.size = pageSize;
      this.getTableList();
    },
    resetParamsHandle() {
      this.searchLeftKey = "";
      this.leftParams.current = 1;
      this.leftParams[this.leftRequstObj.searchKey] = "";
      this.isRequestFlag = false;
      this.isLoadAll = false;
      this.dataList = [];
      this.searchRightKey = "";
      this.rightParams.current = 1;
      this.rightParams.size = 10;
      this.leftParams[this.rightRequstObj.searchKey] = "";
      this.tableData = [];
    },
    searchLeftHandle() {
      this.leftParams[this.leftRequstObj.searchKey] = this.searchLeftKey;
      this.leftParams.current = 1;
      this.dataList = [];
      this.getDataList();
    },
    searchRightHandle() {
      this.rightParams[this.rightRequstObj.searchKey] = this.searchRightKey;
      this.rightParams.current = 1;
      this.$refs.trFooter.currentPage = 1;
      this.getTableList();
    },
    getDataList() {
      this.isRequestFlag = true;
      const { url, method, rlLabel, rlValue, resultKey, urlConfig } =
        this.leftRequstObj;
      getDataList(url, method, this.leftParams, urlConfig)
        .then((res) => {
          if (res.data.code !== 200) return this.$message.error(res.msg);
          let dataKeyList = resultKey.split(",");
          let labelKeyList = rlLabel.split(",");
          let list = [];
          switch (dataKeyList.length) {
            case 1:
              list = res[dataKeyList[0]];
              break;
            case 2:
              list = res[dataKeyList[0]][dataKeyList[1]];
              break;
            case 3:
              list = res[dataKeyList[0]][dataKeyList[1]][dataKeyList[2]];
              break;
          }
          list.forEach((item) => {
            item.rlLabel = "";
            item.rlValue = item[rlValue];
            labelKeyList.forEach((val, idx) => {
              item.rlLabel += item[val];
              if (idx != labelKeyList.length - 1) item.rlLabel += "-";
            });
          });
          this.dataList = [...this.dataList, ...list];
          this.isLoadAll = list.length < this.leftParams.size;
        })
        .finally(() => {
          this.isRequestFlag = false;
        });
    },
    getTableList() {
      const { url, method, resultKey, urlConfig } = this.rightRequstObj;
      getDataList(url, method, this.rightParams, urlConfig).then((res) => {
        if (res.data.code !== 200) return;
        let dataKeyList = resultKey.split(",");
        switch (dataKeyList.length) {
          case 1:
            this.tableData = res[dataKeyList[0]];
            this.totalNum = res[dataKeyList[0]].total;
            break;
          case 2:
            this.tableData = res[dataKeyList[0]][dataKeyList[1]];
            this.totalNum = res[dataKeyList[0]][dataKeyList[1]].total;
            break;
          case 3:
            this.tableData =
              res[dataKeyList[0]][dataKeyList[1]][dataKeyList[2]];
            this.totalNum = res[dataKeyList[0]][dataKeyList[1]].total;
            break;
        }
        this.$validateData(this.tableData);
      });
    },
    initValue() {
      this.leftParams[this.leftRequstObj.searchKey] = "";
      this.rightParams[this.rightRequstObj.searchKey] = "";
      if (Object.keys({ ...this.leftDefaultParams }).length > 0) {
        for (let k in this.leftDefaultParams) {
          this.leftParams[k] = this.leftDefaultParams[k];
        }
      }
      if (Object.keys({ ...this.rightDefaultParams }).length > 0) {
        for (let k in this.rightDefaultParams) {
          this.rightParams[k] = this.rightDefaultParams[k];
        }
      }
      this.selectValue = this.selectModel == "single" ? {} : [];
    },
    chooseHandle(item) {
      if (this.selectModel == "single") {
        if (this.selectValue.rlValue === item.rlValue) return;
        this.selectValue = item;
        this.$emit("single-select", item);
        return;
      }
      if (this.ids.includes(item.rlValue)) {
        this.selectValue = this.selectValue.filter(
          (val) => val.rlValue != item.rlValue
        );
      } else {
        this.selectValue.push(item);
      }
    },
    requestHandle() {
      if (this.isRequestFlag || this.isLoadAll) return;
      this.leftParams.current++;
      this.getDataList();
    },
    closeHandle() {
      this.$emit("update:checkedList", []);
      this.$emit("input", false);
    },
    confrimHandle() {
      if (
        (this.selectModel == "single" &&
          Object.keys(this.selectValue).length < 1) ||
        (this.selectModel != "single" && this.selectValue.length < 1)
      ) {
        this.$message.warning(this.leftEmptyTip);
        return;
      }
      let list = this.$refs.trTable.selectionList;
      if (!this.checkedListSync.length) {
        this.$message.warning(this.rightEmptyTip);
        return;
      }
      let obj = {
        perValue: this.selectValue,
        tabValue: list,
        keysList: this.checkedListSync,
      };
      this.$emit("confrim", obj);
    },
  },
};
</script>

<style lang="scss" scoped>
.power-content-wrap {
  height: 568px;
  .power-left {
    width: 272px;
    .t-item {
      &:hover {
        background-color: $select-hover-background;
      }

      &.checked {
        color: $main-color;
        background-color: $select-active-background;
        .radio-icon {
          border: none;
          background-image: url("~@/assets/icons/circle_active_icon.png");
          background-size: cover;
        }
        .check-icon {
          border: none;
          background-image: url("~@/assets/icons/check_active_icon.png");
          background-size: cover;
        }
      }
    }
    .load-tips {
      text-align: center;
      color: #c0c4cc;
    }
  }
  .power-right {
    flex: 1;
    display: flex;
    flex-direction: column;
    width: 0;
    .right-content-wrap {
      padding: 16px 16px 0 16px;
      flex: 1;
      display: flex;
      flex-direction: column;
    }
  }
}
</style>
